package com.sk.weichat.ui.message.single;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.vlayout.LayoutManagerHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.BaseLayoutHelper;
import com.alibaba.android.vlayout.layout.LayoutChunkResult;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.Label;
import com.sk.weichat.db.dao.LabelDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.CommonAdapter;
import com.sk.weichat.util.CommonViewHolder;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewPiexlUtil;
import com.sk.weichat.view.SelectionFrame;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class SetLabelActivity2 extends BaseActivity implements View.OnClickListener {

    private static final int maxLabels = 20;
    RecyclerView recyclerViewUserLabel;//用户所属标签
    RecyclerView recyclerViewAllLabel; //所有标签
    TextView tv1;
    TextView tv2;
    EditText edtLabel;
    private String mLoginUserId;
    private String mFriendId;
    private List<Label> userLabels = new ArrayList<>();
    private List<Label> allLabels = new ArrayList<>();
    private List<Label> searchLabels = new ArrayList<>();//搜索匹配列表

    private BaseQuickAdapter<Label, BaseViewHolder> userLabelAdapter;
    private BaseQuickAdapter<Label, BaseViewHolder> allLabelAdapter;
    private BaseQuickAdapter<Label, BaseViewHolder> searchLabelAdapter;

    Label deleteLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_label2);
        getSupportActionBar().hide();

        mLoginUserId = coreManager.getSelf().getUserId();
        mFriendId = getIntent().getStringExtra(AppConstant.EXTRA_USER_ID);

        findViewById(R.id.iv_title_left).setOnClickListener(this);
        tv1 = findViewById(R.id.tv1);
        tv2 = findViewById(R.id.tv2);


        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText(R.string.edit_tag);
        TextView tvTitleRight = (TextView) findViewById(R.id.tv_title_right);
        tvTitleRight.setTextColor(getResources().getColor(R.color.colorPrimary));
        tvTitleRight.setText(getString(R.string.sure));
        tvTitleRight.setOnClickListener(this);

        edtLabel = findViewById(R.id.edt_label);
        edtLabel.setSingleLine();
        edtLabel.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_DONE) {
                    if (TextUtils.isEmpty(edtLabel.getText().toString().trim())) {
                        return true;
                    }
                    if (isEnough()) {
                        //判断标签是否超过最大数
                        ToastUtil.showToast(mContext, getString(R.string.tips_max_label_size));
                        return true;
                    }
                    String name = edtLabel.getText().toString().trim();
                    Label label = createNewLabelData(name);
                    if (null != findLabelByNameInAllLabels(name) && null == findLabelByNameInUserLabels(name)) {
                        Label label1 = findLabelByNameInAllLabels(name);
                        label1.setSelected(true);
                        userLabels.add(label1);
                        userLabelAdapter.notifyItemInserted(userLabels.size());
                        allLabelAdapter.notifyItemChanged(allLabels.indexOf(label1));
                    } else if (null == findLabelByNameInUserLabels(name)) {
                        userLabels.add(label);
                        userLabelAdapter.notifyItemInserted(userLabels.size());
                    }
                    if (null == findLabelByNameInAllLabels(name)) {
                        allLabels.add(label);
                        allLabelAdapter.notifyItemInserted(allLabels.size());
                    }
                    edtLabel.setText("");
                    if (searchPopuWindow != null) {
                        searchPopuWindow.dismiss();
                    }
                    if (userLabels.size() == 0) {
                        adjustEmpty(true);
                    } else {
                        adjustEmpty(false);
                    }
                    return true;
                }
                return false;
            }
        });

        edtLabel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                List<Label> list = check(s.toString());
                if (list.size() > 0) {
                    searchLabels.clear();
                    searchLabels.addAll(list);
                    setupSearchPopuWindow();
                    searchLabelAdapter.notifyDataSetChanged();
                    searchPopuWindow.showAsDropDown(edtLabel, 0, 0);
                }
                if (TextUtils.isEmpty(s.toString())) {
                    if (userLabels.size() != 0) {
                        adjustEmpty(false);
                    }
                    if (searchPopuWindow != null) {
                        searchPopuWindow.dismiss();
                    }
                    tv2.setVisibility(View.VISIBLE);
                    recyclerViewAllLabel.setVisibility(View.VISIBLE);
                    recyclerViewUserLabel.setVisibility(View.VISIBLE);
                } else {
                    tv1.setVisibility(View.GONE);
                    tv2.setVisibility(View.GONE);
                    recyclerViewAllLabel.setVisibility(View.GONE);
                    recyclerViewUserLabel.setVisibility(View.GONE);
                }
            }
        });

        recyclerViewUserLabel = findViewById(R.id.recyclerview_user_label);
        //流式布局
        FlexboxLayoutManager layoutManager1 = new FlexboxLayoutManager(mContext);
        layoutManager1 = new FlexboxLayoutManager(mContext);
        layoutManager1.setFlexDirection(FlexDirection.ROW);
        layoutManager1.setJustifyContent(JustifyContent.FLEX_START);
        layoutManager1.setFlexWrap(FlexWrap.WRAP);
        recyclerViewUserLabel.setLayoutManager(layoutManager1);

        userLabelAdapter = new BaseQuickAdapter<Label, BaseViewHolder>(R.layout.item_label, userLabels) {

            @Override
            protected void convert(BaseViewHolder holder, Label item) {
                holder.addOnLongClickListener(R.id.tv_label);
                holder.addOnClickListener(R.id.tv_label);
                TextView tvLabel = holder.getView(R.id.tv_label);
                tvLabel.setSelected(true);
                tvLabel.setText(item.getGroupName());
            }
        };
        userLabelAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                //长按删除，弹出pupowindow
                deleteLabel = userLabels.get(position);
                view.setPressed(true);
                setupDeletePopuWindow();
                deletePopuWindow.showAsDropDown(view, 0, -(view.getHeight() + ViewPiexlUtil.dp2px(mContext, 44)));
                return true;
            }
        });

        recyclerViewUserLabel.setAdapter(userLabelAdapter);


        recyclerViewAllLabel = findViewById(R.id.recyclerview_all_label);

        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(mContext);
        layoutManager = new FlexboxLayoutManager(mContext);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        recyclerViewAllLabel.setLayoutManager(layoutManager);
        allLabelAdapter = new BaseQuickAdapter<Label, BaseViewHolder>(R.layout.item_label, allLabels) {

            @Override
            protected void convert(BaseViewHolder holder, Label item) {
                holder.addOnClickListener(R.id.tv_label);
                TextView tvLabel = holder.getView(R.id.tv_label);
                if (item.isSelected()) {
                    tvLabel.setSelected(true);
                } else {
                    tvLabel.setSelected(false);
                }
                tvLabel.setText(item.getGroupName());
            }
        };
        allLabelAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (allLabels.get(position).isSelected()) {
                    //取消选中
                    int index = userLabels.indexOf(allLabels.get(position));
                    userLabels.remove(allLabels.get(position));
                    allLabels.get(position).setSelected(false);
                    userLabelAdapter.notifyItemRemoved(index);
                } else {
                    //选中
                    userLabels.add(allLabels.get(position));
                    allLabels.get(position).setSelected(true);
                    userLabelAdapter.notifyDataSetChanged();
                }
                if (userLabels.size() == 0) {
                    adjustEmpty(true);
                } else {
                    adjustEmpty(false);
                }
                allLabelAdapter.notifyItemChanged(position);
            }
        });
        recyclerViewAllLabel.setAdapter(allLabelAdapter);
        //获取标签
        getLabels();
    }

    /**
     * 完全搜索匹配
     *
     * @param labelName
     * @return
     */
    private List<Label> check(String labelName) {
        List<Label> labels = new ArrayList<>();
        for (int i = 0; i < allLabels.size(); i++) {
            if (allLabels.get(i).getGroupName().equals(labelName)) {
                labels.add(allLabels.get(i));
            }
        }
        return labels;
    }


    /**
     * 获得该用户所属的标签
     */
    private void loadData(List<Label> allLabelList) {
        for (int i = 0; i < allLabelList.size(); i++) {
            if (allLabelList.get(i).getUserIdList().contains(mFriendId)) {
                userLabels.add(allLabelList.get(i));
                allLabelList.get(i).setSelected(true);
                // Log.e("lzs", "userLabel:" + allLabelList.get(i));
            }
        }
        if (userLabels.size() == 0) {
            adjustEmpty(true);
        } else {
            adjustEmpty(false);
        }

        if (allLabelList.size() == 0) {
            adjustEmpty2(true);
        } else {
            adjustEmpty2(false);
        }
        userLabelAdapter.notifyDataSetChanged();

        allLabels.addAll(allLabelList);
        allLabelAdapter.notifyDataSetChanged();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                SelectionFrame selectionFrame = new SelectionFrame(mContext);
                selectionFrame.setSomething(getString(R.string.dialog_title), getString(R.string.tips_save_label), getString(R.string.not_save_label), getString(R.string.save_label), new SelectionFrame.OnSelectionFrameClickListener() {
                    @Override
                    public void cancelClick() {
                        //finish
                        finish();
                    }

                    @Override
                    public void confirmClick() {
                        //保存
                        saveLabels();
                    }
                });
                selectionFrame.show();
                break;
            case R.id.tv_title_right:
                //确定
                saveLabels();
                break;
        }
    }

    private Label createNewLabelData(String name) {
        Label label = new Label();
        label.setSelected(true);
        label.setGroupName(edtLabel.getText().toString().trim());
        label.setUserId(mLoginUserId);
        return label;
    }

    private Label findLabelByNameInAllLabels(String name) {
        //判断是否有重复的标签
        for (int i = 0; i < allLabels.size(); i++) {
            if (allLabels.get(i).getGroupName().equals(name)) {
                return allLabels.get(i);
            }
        }
        return null;
    }

    private Label findLabelByNameInUserLabels(String name) {
        //判断是否有重复的标签
        for (int i = 0; i < userLabels.size(); i++) {
            if (userLabels.get(i).getGroupName().equals(name)) {
                return userLabels.get(i);
            }
        }
        return null;
    }

    private void saveLabels() {
        String name = edtLabel.getText().toString().trim();
        if (!TextUtils.isEmpty(name)) {
            Label label = createNewLabelData(name);
            if (null == findLabelByNameInUserLabels(name)) {
                if (isEnough()) {
                    //判断标签是否超过最大数
                    ToastUtil.showToast(mContext, getString(R.string.tips_max_label_size));
                    return;
                }
                userLabels.add(label);
                userLabelAdapter.notifyItemInserted(userLabels.size());
            }
            if (null == findLabelByNameInAllLabels(name)) {
                allLabels.add(label);
                allLabelAdapter.notifyItemInserted(allLabels.size());
            }
        }
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < userLabels.size(); i++) {
            if (TextUtils.isEmpty(userLabels.get(i).getGroupId())) {
                createLabel(userLabels.get(i).getGroupName());
            } else {
                ids.add(userLabels.get(i).getGroupId());
            }
        }
        if (ids.size() == userLabels.size()) {
            //
            updateLabelUserIdList(ids);
        }
    }

    // 创建标签
    private void createLabel(final String groupName) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("groupName", groupName);

        HttpUtils.get().url(coreManager.getConfig().FRIENDGROUP_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<Label>(Label.class) {
                    @Override
                    public void onResponse(ObjectResult<Label> result) {
                        if (result.getResultCode() == 1) {
                            List<String> ids = new ArrayList<>();

                            for (int i = 0; i < userLabels.size(); i++) {
                                if (userLabels.get(i).getGroupName().equals(result.getData().getGroupName())) {
                                    userLabels.get(i).setGroupId(result.getData().getGroupId());
                                }
                                ids.add(userLabels.get(i).getGroupId());
                            }
                            //更新选择的标签
                            updateLabelUserIdList(ids);
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    // 更新选中的标签lUserIdList
    private void updateLabelUserIdList(final List<String> groupIdList) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", mFriendId);
        String groupIdStr = "";
        for (int i = 0; i < groupIdList.size(); i++) {
            if (i == groupIdList.size() - 1) {
                groupIdStr += groupIdList.get(i);
            } else {
                groupIdStr += groupIdList.get(i) + ",";
            }
        }
        params.put("groupIdStr", groupIdStr);
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().FRIENDGROUP_UPDATEFRIEND)
                .params(params)
                .build()
                .execute(new BaseCallback<Label>(Label.class) {
                    @Override
                    public void onResponse(ObjectResult<Label> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            finish();
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    PopupWindow deletePopuWindow;

    private void setupDeletePopuWindow() {
        if (deletePopuWindow != null)
            return;
        deletePopuWindow = new PopupWindow(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        deletePopuWindow.setOutsideTouchable(true);
        deletePopuWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View view = LayoutInflater.from(mContext).inflate(R.layout.popu_delete_label_item, null);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除标签
                int index = userLabels.indexOf(deleteLabel);
                userLabels.remove(deleteLabel);
                userLabelAdapter.notifyItemRemoved(index);

                index = allLabels.indexOf(deleteLabel);
                deleteLabel.setSelected(false);
                allLabelAdapter.notifyItemChanged(index);
                deletePopuWindow.dismiss();
                if (userLabels.size() == 0) {
                    adjustEmpty(true);
                } else {
                    adjustEmpty(false);
                }
            }
        });
        deletePopuWindow.setContentView(view);
    }

    PopupWindow searchPopuWindow;

    /**
     * 匹配搜索
     */
    private void setupSearchPopuWindow() {
        if (searchPopuWindow != null)
            return;
        searchPopuWindow = new PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        searchPopuWindow.setOutsideTouchable(true);
        searchPopuWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View view = LayoutInflater.from(mContext).inflate(R.layout.popu_label_search_list, null);
        RecyclerView searchList = view.findViewById(R.id.recyclerview);
        searchList.setLayoutManager(new LinearLayoutManager(mContext));
        searchLabelAdapter = new BaseQuickAdapter<Label, BaseViewHolder>(R.layout.item_label_search, searchLabels) {
            @Override
            protected void convert(BaseViewHolder holder, Label item) {
                holder.addOnClickListener(R.id.tv_label);
                holder.setText(R.id.tv_label, item.getGroupName());
            }
        };
        searchLabelAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (!userLabels.contains(searchLabels.get(position))) {
                    //选择该标签
                    userLabels.add(searchLabels.get(position));
                    userLabelAdapter.notifyItemInserted(userLabels.size());
                    int index = allLabels.indexOf(searchLabels.get(position));
                    searchLabels.get(position).setSelected(true);
                    allLabelAdapter.notifyItemChanged(index);
                    adjustEmpty(false);
                }
                edtLabel.setText("");
                searchPopuWindow.dismiss();
            }
        });
        searchList.setAdapter(searchLabelAdapter);
        searchPopuWindow.setContentView(view);
    }


    // 获取标签数据
    private void getLabels() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().FRIENDGROUP_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<Label>(Label.class) {
                    @Override
                    public void onResponse(ArrayResult<Label> result) {
                        if (result.getResultCode() == 1) {
                            List<Label> labelList = result.getData();
                            LabelDao.getInstance().refreshLabel(mLoginUserId, labelList);
                            loadData(labelList);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    /**
     * 判断是否达到标签最大数最大
     */
    private boolean isEnough() {
        return allLabels.size() >= maxLabels;
    }

    /**
     *
     */
    private void adjustEmpty(boolean isEmpty) {
        Log.e("lzs", "isEmpty:" + isEmpty);
        if (isEmpty) {
            findViewById(R.id.tv1).setVisibility(View.GONE);
            recyclerViewUserLabel.setVisibility(View.GONE);
        } else {
            findViewById(R.id.tv1).setVisibility(View.VISIBLE);
            recyclerViewUserLabel.setVisibility(View.VISIBLE);
        }
    }

    private void adjustEmpty2(boolean isEmpty) {
        Log.e("lzs", "isEmpty:" + isEmpty);
        if (isEmpty) {
            findViewById(R.id.tv2).setVisibility(View.GONE);
            recyclerViewAllLabel.setVisibility(View.GONE);
        } else {
            findViewById(R.id.tv2).setVisibility(View.VISIBLE);
            recyclerViewAllLabel.setVisibility(View.VISIBLE);
        }
    }
}
